package com.hg.filter;


import com.alibaba.fastjson.JSON;
import com.hg.common.BaseContext;
import com.hg.common.HttpStatus;
import com.hg.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@CrossOrigin
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的uri
        String requestURI = request.getRequestURI();
        //定义不需要拦截的路径
        String[] urls = new String[]{
                "/hbgc/user/login",
                "/hbgc/user/register",
                "/hbgc/**/export",
                "/hbgc/**/import",
                "/hbgc/user/captcha",
                "/hbgc/file/**",
                "/hbgc/**/*.html",
                "/hbgc/**/*.js",
                "/hbgc/**/*.css",
                "/hbgc/**/*.woff",
                "/hbgc/**/*.ttf",
                "/hbgc/v2/api-docs"
        };

        //2.判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //3.如果不需要处理，就直接放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //4.判断登录状态，如果已经登录，直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        System.out.println("11111111111111111111112"+userId);
        if (userId != null){

            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //5.如果未登录则返回未登录结果，通过输出流的方式向客户端响应数据
        response.getWriter().write((JSON.toJSONString(R.error(HttpStatus.LOGOUT_ERROR,"请先登入"))));
        return;
    }

    @Override
    public void destroy() {

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestUri
     * @return
     */
    public boolean check(String[] urls, String requestUri){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
